/*
 * Copyright (c) 2023 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <mc/log.h>

#include "interface/network_port/metrics.h"

namespace dev {

bool NetworkPort_Metrics::update_port_metrics_by_ncsi(uint8_t port_id) {
    ncsi_port_metrics_info_t port_metrics = {};
    bool                     ret =
        m_ncsi_over_mctp_huawei->get_port_metrics(DEFAULT_PACKAGE_ID, port_id, &port_metrics);
    if (!ret) {
        elog("Error: Failed to update port metrics");
        return false;
    }

    // 使用模板函数简化条件赋值操作
    RXFrames.set_value(port_metrics.rx_frames);
    TXFrames.set_value(port_metrics.tx_frames);
    RXUnicastFrames.set_value(port_metrics.rx_unicast_frames);
    TXUnicastFrames.set_value(port_metrics.tx_unicast_frames);
    RXMulticastFrames.set_value(port_metrics.rx_multicast_frames);
    TXMulticastFrames.set_value(port_metrics.tx_multicast_frames);
    RXBroadcastFrames.set_value(port_metrics.rx_broadcast_frames);
    TXBroadcastFrames.set_value(port_metrics.tx_broadcast_frames);
    RXFCSErrors.set_value(port_metrics.rx_fcs_errors);
    RXUndersizeFrames.set_value(port_metrics.rx_under_size_frames);
    RXOversizeFrames.set_value(port_metrics.rx_over_size_frames);
    TXSingleCollisions.set_value(port_metrics.tx_single_collisions);
    TXMultipleCollisions.set_value(port_metrics.tx_multiple_collisions);
    TXLateCollisions.set_value(port_metrics.tx_late_collisions);
    TXExcessiveCollisions.set_value(port_metrics.tx_excessive_collisions);
    RXFrameAlignmentErrors.set_value(port_metrics.rx_frame_alignment_errors);
    return true;
}

void NetworkPort_Metrics::start_ncsi_update_task_huawei(ncsi_over_mctp_hw_ptr ncsi_over_mctp,
                                                        mc::milliseconds      interval,
                                                        uint8_t               port_id) {
    m_ncsi_over_mctp_huawei = ncsi_over_mctp;
    m_ncsi_timer            = new mc::core::timer(this);
    m_ncsi_timer->timeout.connect([this, port_id]() {
        update_port_metrics_by_ncsi(port_id);
    });
    m_ncsi_timer->set_single_shot(false);
    m_ncsi_timer->start(interval);
}

void NetworkPort_Metrics::stop_ncsi_update_task() {
    if (m_ncsi_timer) {
        m_ncsi_timer->stop();
        delete m_ncsi_timer;
        m_ncsi_timer = nullptr;
    }
    if (m_ncsi_over_mctp_huawei) {
        m_ncsi_over_mctp_huawei = nullptr;
    }
}

} // namespace dev

MC_REFLECT(dev::NetworkPort_Metrics)